import domUtils from "./core/domUtils";
import Selection from "./core/Selection";
import browser from "./core/browser";
let _selectionChangeTimer;

class Editor {
  constructor() {
    this.selection = new Selection(document);
    const me = this;
    // domUtils.on(document, ["mouseup", "keydown"], function (evt) {
    //   if (
    //     evt.type == "keydown" &&
    //     (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)
    //   ) {
    //     return;
    //   }
    //   if (evt.button == 2) return;
    //   me._selectionChange(250, evt);
    // })
  }

  _selectionChange(delay, evt) {
    var me = this;
    //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题（source命令notNeedUndo=1）
    //            if ( !me.selection.isFocus() ){
    //                return;
    //            }

    var hackForMouseUp = false;
    var mouseX, mouseY;
    if (browser.ie && browser.version < 9 && evt && evt.type == "mouseup") {
      var range = this.selection.getRange();
      if (!range.collapsed) {
        hackForMouseUp = true;
        mouseX = evt.clientX;
        mouseY = evt.clientY;
      }
    }
    clearTimeout(_selectionChangeTimer);
    _selectionChangeTimer = setTimeout(function () {
      if (!me.selection || !me.selection.getNative()) {
        return;
      }
      //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时，可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
      //IE下如果用户是拖拽一段已选择文本，则不会触发mouseup事件，所以这里的特殊处理不会对其有影响
      var ieRange;
      if (hackForMouseUp && me.selection.getNative().type == "None") {
        ieRange = me.document.body.createTextRange();
        try {
          ieRange.moveToPoint(mouseX, mouseY);
        } catch (ex) {
          ieRange = null;
        }
      }
      var bakGetIERange;
      if (ieRange) {
        bakGetIERange = me.selection.getIERange;
        me.selection.getIERange = function () {
          return ieRange;
        };
      }
      me.selection.cache();
      if (bakGetIERange) {
        me.selection.getIERange = bakGetIERange;
      }
      if (me.selection._cachedRange && me.selection._cachedStartElement) {
        me.fireEvent("beforeselectionchange");
        // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
        me.fireEvent("selectionchange", !!evt);
        me.fireEvent("afterselectionchange");
        me.selection.clear();
      }
    }, delay || 50);
  }
}

export default new Editor();